﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TerrainGenerator
{
    class Triangle
    {
        public int Index { get { return index; } }

        int index;

        public int X1 { get { return x1; } }
        public int Y1 { get { return y1; } }
        public int X2 { get { return x2; } }
        public int Y2 { get { return y2; } }
        public int X3 { get { return x3; } }
        public int Y3 { get { return y3; } }

        int x1, y1; // coordinates of left vertex
        int x2, y2; // coordinates of center vertex
        int x3, y3; // coordinates of right vertex

        public Triangle(int index, int x1, int y1, int x2, int y2, int x3, int y3)
        {
            this.index = index;

            this.x1 = x1;
            this.y1 = y1;
            this.x2 = x2;
            this.y2 = y2;
            this.x3 = x3;
            this.y3 = y3;
        }

        public Triangle LeftChild()
        {
            if (IsLeaf())
                return null;

            int x = (x1 + x3) >> 1;
            int y = (y1 + y3) >> 1;
            return new Triangle(index * 2 + 1, x2, y2, x, y, x1, y1);
        }

        public Triangle RightChild()
        {
            if (IsLeaf())
                return null;

            int x = (x1 + x3) >> 1;
            int y = (y1 + y3) >> 1;
            return new Triangle(index * 2 + 2, x3, y3, x, y, x2, y2);
        }

        public bool IsLeaf()
        {
            return Math.Abs(x1 - x3) == 1 || Math.Abs(y1 - y3) == 1;
        }

        public float Variance(float[,] heightmap)
        {
            float z1 = heightmap[x1, y1];
            float z3 = heightmap[x3, y3];
            
            int x = (x1 + x3) >> 1;
            int y = (y1 + y3) >> 1;
            float z = heightmap[x, y];

            return Math.Abs(z - (z1 + z3) / 2);
        }
    }
}
